<template>
  <div class="my-detail-box">
    <div class="my-content-box df aic jcsb mb9" style="height: 51px">
      <div class="icon-box df aic" @click="handleClose()">
        <i class="iconfont icon-fanhui1"></i>
        <span>返回</span>
      </div>
      <div class="detail-btn df aic">
        <div v-if="!tableId" class="btn btn-approve" @click="handleSubmit()">
          <i class="iconfont icon-dui"></i>保存
        </div>
        <template v-else>
          <div v-if="!state.isEdit" class="btn btn-approve" @click="handleEdit()">
            <i class="iconfont icon-bianji4"></i>编辑
          </div>
          <div v-if="state.isEdit" class="btn btn-reject" @click="handleEditClose()">
            <i class="iconfont icon-yijianfoujue"></i>取消
          </div>
          <div v-if="state.isEdit" class="btn btn-approve" @click="handleSubmit()">
            <i class="iconfont icon-dui"></i>保存
          </div>
        </template>
      </div>
    </div>
    <div class="my-content-box mb9">
      <div class="title-box df aic mb9">
        <div class="title-icon"></div>
        <div class="title">报表信息</div>
      </div>
      <el-form
        ref="formRef"
        :model="state.formData"
        :rules="state.formRules"
        label-width="auto"
        class="my-form-box2 df aic"
      >
        <el-form-item label="报表名称:" prop="reportName">
          <el-input
            v-model="state.formData.reportName"
            :disabled="isDisabled()"
            placeholder="请输入报表名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="报表标题:" prop="reportTitle">
          <el-input
            v-model="state.formData.reportTitle"
            :disabled="isDisabled()"
            placeholder="请输入报表标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否统计集团数据:" prop="statisticsCorporationData">
          <el-select v-model="state.formData.statisticsCorporationData" :disabled="isDisabled()">
            <el-option
              v-for="(item, index) in statisticsCorporationDataDics"
              :key="index"
              :label="`${item.name}`"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <div class="my-content-box mb9">
      <div class="df aic jcsb mb9">
        <div class="title-box df aic">
          <div class="title-icon"></div>
          <div class="title">报表预览</div>
        </div>
        <div class="detail-btn">
          <div class="btn btn-approve" @click="previewTable">生成预览图</div>
        </div>
      </div>
      <div class="preview-box">
        <div v-if="state.tablePreviewList.length == 0" class="preview-text">请点击“生成预览图”查看</div>
        <table-page-content
          v-else
          class="preview-table"
          :table-data="[]"
          :table-headers="state.tablePreviewList"
          :table-height="'140px'"
          :is-slot-num="false"
          :is-pager="false"
          :is-more-header="true"
        ></table-page-content>
      </div>
    </div>
    <div class="my-content-box">
      <div class="df aic jcsb mb9">
        <div class="title-box df aic">
          <div class="title-icon"></div>
          <div class="title">报表表头定义</div>
        </div>
        <div class="detail-btn">
          <div class="btn btn-approve" @click="addItem()">新建单元格</div>
        </div>
      </div>
      <table-page-content
        class="cell-table"
        :table-data="state.tableList"
        :table-headers="tableDetailHeaders"
        :table-height="'45vh'"
        :tree-props="{ children: 'children' }"
        :row-key="'timeId'"
        :is-pager="false"
        :is-slot-num="false"
      >
        <template #cellName="{ row }">
          <el-input v-model="row.cellName" :disabled="isDisabled()" placeholder="请输入描述"></el-input>
        </template>
        <template #cellWidth="{ row }">
          <el-input v-model="row.cellWidth" :disabled="isDisabled()" placeholder="请输入宽度"></el-input>
        </template>
        <template #cellAlignment="{ row }">
          <el-select v-model="row.cellAlignment" :disabled="isDisabled()" placeholder="请选择对齐方式">
            <el-option
              v-for="item in cellAlignmentDics"
              :key="item.code"
              :label="`${item.name}`"
              :value="item.code"
            />
          </el-select>
        </template>
        <template #status="{ row }">
          <el-select v-model="row.status" :disabled="isDisabled()" placeholder="请选择使用状态">
            <el-option
              v-for="item in cellStatusDics"
              :key="item.code"
              :label="`${item.code} - ${item.name}`"
              :value="item.code"
            />
          </el-select>
        </template>
        <template #isSum="{ row }">
          <el-select v-model="row.isSum" :disabled="isDisabled()" placeholder="请选择是否小计">
            <el-option
              v-for="item in cellIsSumDics"
              :key="item.code"
              :label="`${item.code} - ${item.name}`"
              :value="item.code"
            />
          </el-select>
        </template>
        <template #sumPosition="{ row }">
          <el-select v-model="row.sumPosition" :disabled="isDisabled()" placeholder="请选择小计位置">
            <el-option
              v-for="item in cellSumPositionDics"
              :key="item.code"
              :label="`${item.code} - ${item.name}`"
              :value="item.code"
            />
          </el-select>
        </template>
        <template #cellDataKey="{ row }">
          <el-select v-model="row.cellDataKey" filterable :disabled="isDisabled()" placeholder="请选择关键字">
            <el-option
              v-for="item in state.cellDataKeyList"
              :key="item.dataKey"
              :label="`${item.dataKeyName}`"
              :value="item.dataKey"
            />
          </el-select>
        </template>
        <template #operate="{ row }">
          <div class="table-btn-box">
            <el-button :class="isDisabled() ? 'disable-btn' : ''" link @click="addItem(row)"
              ><i class="iconfont icon-xiaji"></i><span class="text">创建下级</span></el-button
            >
            <!-- :disabled="isDisabled()" -->
            <el-button :class="isDisabled() ? 'disable-btn' : ''" link @click="SshowTabBody(row)"
              ><span class="text">设置</span></el-button
            >
            <el-button :class="isDisabled() ? 'disable-btn' : ''" link @click="delItem(row)">
              <i class="iconfont icon-tubiaozhizuomoban"></i><span class="text">删除</span>
            </el-button>
          </div>
        </template>
      </table-page-content>
    </div>
  </div>

  <!-- 报表表体设置 2023/12/21 -->
  <draw-component
    :drawer-visible="state.showTabBody"
    size="410px"
    title="表体设置"
    @close-drawer="state.showTabBody = false"
    @save-drawer="handleSubmit"
  >
    <div class="BodyDataStyle">
      <el-form label-width="120px">
        <el-form-item label="单元格描述">
          <el-input v-model="state.BodyData.cellName" disabled />
        </el-form-item>
        <!-- <el-form-item label="选择合并方式：" label-width="120px">
          <el-select v-model="state.BodyData.direction" placeholder="选择合并方式">
            <el-option label="向左" value="left" />
            <el-option label="向下" value="bottom" />
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="固定数值合并：">
          <el-switch v-model="state.BodyData.regular" />
        </el-form-item>
        <el-form-item label="单元格描述：" v-if="state.BodyData.regular">
          <el-input v-model="state.BodyData.regularNum" />
        </el-form-item>-->
        <el-form-item label="向下合并">
          <el-input v-model="state.BodyData.rowspan" placeholder="1为初始值，-1为自动" />
        </el-form-item>
        <el-form-item label="向左合并">
          <el-input v-model="state.BodyData.colspan" placeholder="1为初始值,取消合并" />
        </el-form-item>
      </el-form>
    </div>
  </draw-component>
</template>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { useProxy } from '@/utils/proxy'
import { tableDetailHeaders } from './config'
import { editSubmit, addSubmit, getDataKeyList, getDetailById } from './api'
import {
  cellAlignmentDics,
  cellIsSumDics,
  cellStatusDics,
  cellSumPositionDics,
  statisticsCorporationDataDics
} from '@/hooks/dicsData'
const { proxy } = useProxy()
const formRef = ref<FormInstance>()
const tableId = proxy.$route.query && (proxy.$route.query.tableId as string)
const state = reactive({
  isSubmiting: false,
  isEdit: false,
  formData: { reportName: '', reportTitle: '', statisticsCorporationData: true },
  cellDataKeyList: [] as any[],
  tableList: [] as any[],
  tablePreviewList: [] as any[],
  formRules: {
    reportName: [{ required: true, message: '请输入报表名称', trigger: 'blur' }],
    reportTitle: [{ required: true, message: '请输入报表标题', trigger: 'blur' }]
  } as FormRules,
  showTabBody: !true,
  BodyData: {
    cellName: '',
    rowspan: '',
    colspan: ''
  }
})
// 返回
const handleClose = () => {
  proxy.$router.go(-1)
}
const TabBodyhandleClose = () => {
  // state.showTabBody = false
}
interface MyObjectType {
  cellName: string
  rowspan: number
  colspan: number
}

interface StateType {
  BodyData: MyObjectType
}

const SshowTabBody = (row: Record<string, unknown>): void => {
  state.BodyData = row as unknown as MyObjectType
  state.showTabBody = true
  return
}
// 保存
const handleSubmit = async () => {
  return console.log(state.tableList)
  /** 
  await formRef.value?.validate(async (valid) => {
    if (valid) {
      if (state.tableList.length == 0) {
        return proxy.$message.msgError('请至少新增一条单元格')
      }
      let validMsg = mapValidTree(state.tableList, '')
      if (validMsg) {
        return proxy.$message.msgError(validMsg)
      }
      if (state.isSubmiting) return
      state.isSubmiting = true
      if (tableId) {
        editSubmit(tableId, { ...state.formData, status: 1, details: state.tableList })
          .then(() => {
            proxy.$message.msgSuccess('编辑成功')
            state.isSubmiting = false
            handleClose()
          })
          .catch(() => {
            state.isSubmiting = false
          })
      } else {
        addSubmit({ ...state.formData, details: state.tableList })
          .then(() => {
            proxy.$message.msgSuccess('新增成功')
            state.isSubmiting = false
            handleClose()
          })
          .catch(() => {
            state.isSubmiting = false
          })
      }
    } else {
      formRef.value!.scrollToField('reportName')
    }
  })
*/
}
// 是否禁止编辑
const isDisabled = (): boolean => {
  if (tableId && !state.isEdit) {
    return true
  } else {
    return false
  }
}
//编辑
const handleEdit = () => {
  state.isEdit = true
}
// 取消编辑
const handleEditClose = () => {
  state.isEdit = false
}
// 新增单元格
const addItem = (row?: any) => {
  if (isDisabled()) return
  let item = {
    timeId: new Date().valueOf(),
    cellName: '',
    cellWidth: '100',
    cellAlignment: 'center',
    status: '1',
    isSum: '1',
    sumPosition: '0',
    cellDataKey: '',
    children: [],
    rowspan: '',
    colspan: ''
  }
  if (row) {
    row.children.push(item)
  } else {
    state.tableList.push(item)
  }
}
// 删除单元格
const delItem = (row: any) => {
  if (isDisabled()) return
  mapDelTree(state.tableList, 'timeId', row.timeId)
}
//递归遍历树,删除查询节点
const mapDelTree = (treeData: any[], key: any, value: any) => {
  for (let index = 0; index < treeData.length; index++) {
    const item = treeData[index]
    if (item[key] == value) {
      treeData.splice(index, 1)
      break
    }
    if (item.children.length > 0) {
      mapDelTree(item.children, key, value)
    }
  }
}
// 递归遍历树,校验字段
const mapValidTree = (treeData: any[], errorText: string): string => {
  const reg = /(^[1-9]\d*$)/
  for (let index = 0; index < treeData.length; index++) {
    const item = treeData[index]
    if (!item.cellName) {
      errorText = '单元格描述不能为空!'
      break
    }
    if (item.cellWidth && !reg.test(item.cellWidth)) {
      errorText = '宽度只能输入正整数!'
      break
    }
    if (item.children.length == 0 && !item.cellDataKey) {
      errorText = '最下级必须选择关键字'
      break
    }
    if (item.children.length > 0) {
      errorText = mapValidTree(item.children, errorText)
    }
  }
  return errorText
}
// 处理小计
const getTotalItem = (treeData: any[]) => {
  treeData.forEach((v) => {
    if (v?.children?.length) {
      if (v.isSum == '1') {
        let item = {
          cellName: '小计',
          cellWidth: 60,
          cellAlignment: 'center',
          cellDataKey: ''
        } as any
        v.sumPosition == '0' ? v.children.unshift(item) : v.children.push(item)
      }
      getTotalItem(v.children)
    }
  })
  return treeData
}
// 预览
const previewTable = () => {
  if (state.tableList.length == 0) {
    return proxy.$message.msgError('请至少新增一条单元格')
  }
  let valid = mapValidTree(state.tableList, '')
  if (valid) {
    return proxy.$message.msgError(valid)
  }
  state.tablePreviewList = getTotalItem(JSON.parse(JSON.stringify(state.tableList)))
}
// 获取关键字列表
const getDataKey = () => {
  getDataKeyList().then((res) => {
    state.cellDataKeyList = res.data
  })
}
// 获取详情
const getDetail = () => {
  getDetailById(tableId).then((res) => {
    state.formData.reportName = res.data.reportName
    state.formData.reportTitle = res.data.reportTitle
    state.formData.statisticsCorporationData = res.data.statisticsCorporationData || false
    state.tableList = getTimeIdItem(res.data.details)
    state.tablePreviewList = getTotalItem(JSON.parse(JSON.stringify(res.data.details)))
  })
}
// 处理id
const getTimeIdItem = (treeData: any[]) => {
  treeData.forEach((v) => {
    v.timeId = v.id
    if (v?.children?.length) {
      getTimeIdItem(v.children)
    }
  })
  return treeData
}
getDataKey()
if (tableId) getDetail()
</script>

<style lang="scss" scoped>
.mb9 {
  margin-bottom: 9px;
}
.cell-table {
  :deep(.el-table__row td:first-child .cell) {
    display: flex;
    align-items: center;
  }
}

.my-form-box2 {
  :deep(.el-form-item:not(:last-child)) {
    margin-right: 60px;
  }
  :deep(.el-form-item) {
    margin-bottom: 9px;
  }
}
.title-box {
  .title-icon {
    width: 4px;
    height: 28px;
    background: #558df7;
    border-radius: 2px 2px 2px 2px;
    margin-right: 9px;
  }
  .title {
    font-size: 20px;
    font-weight: bold;
    color: #333333;
  }
}
.preview-box {
  position: relative;
  width: 100%;
  height: 158px;
  background: #f2f2f2;
  border-radius: 4px 4px 4px 4px;
  border: 1px dashed #cccccc;
  padding: 9px;
  box-sizing: border-box;
  .preview-table {
    border: 1px solid #ccc;
    :deep(.el-table__body-wrapper) {
      display: none;
    }
    :deep(.el-table__header-wrapper) {
      overflow: auto;
    }
    :deep(.el-table__inner-wrapper) {
      overflow: auto;
    }
  }
  .preview-text {
    display: inline-block;
    font-size: 16px;
    font-weight: 400;
    color: #999999;
    position: relative;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}
</style>
<style lang="scss">
.BodyDataStyle {
  .el-input {
    width: 210px;
  }
}
</style>
